<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="图号">
          <el-select
            style="width: 100%"
            v-model="searchParam.figureNumber"
            placeholder="请选择图号"
            clearable
          >
            <el-option
              v-for="item in materialProcessList"
              :label="`${item.materialProcessFigure}`"
              :value="`${item.materialProcessFigure}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产单位" prop="supplyId">
          <!-- <el-select
            style="width: 100%"
            v-model="searchParam.supplyId"
            placeholder="请输入生产单位"
            clearable
          >
            <el-option
              v-for="item in supplyList"
              :label="`${item.partnerCode}-${item.partnerName}`"
              :value="`${item.id}`"
            />
          </el-select> -->

          <el-input
            v-model="searchParam.supplyName"
            placeholder="请输入生产单位"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="发生时间">
          <el-date-picker
            v-model="searchParam.occurrenceTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getoccurrenceTime"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <!-- <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        > -->
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="异常信息编号"
          prop="qualityExceptionCode"
          min-width="180"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="状态"
          prop="exceptionState"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{
              dictionaryStore.filterDictName(
                "ExceptionState",
                scope.row.exceptionState
              )
            }}
          </template>
        </el-table-column>

        <el-table-column
          label="产品类目"
          prop="productionTypeName"
          min-width="180"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="产品图号"
          prop="figureNumber"
          min-width="180"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="产品名称"
          prop="materialName"
          min-width="180"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column
          label="数量"
          prop="exceptionQuantity"
          min-width="100"
          show-overflow-tooltip
          align="right"
        >
        </el-table-column>
        <el-table-column
          label="失效模式"
          prop="failureModeContent"
          min-width="180"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="失效对应数量"
          prop="failureQuantity"
          min-width="180"
          show-overflow-tooltip
          align="right"
        >
        </el-table-column>

        <el-table-column
          label="发生时间"
          prop="occurrenceTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{
              scope.row.occurrenceTime
                ? dayjs(scope.row.occurrenceTime).format("YYYY-MM-DD")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="发生地点"
          prop="occurrenceLocation"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="信息来源"
          prop="informationSourceContent"
          min-width="180"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="生产单位"
          prop="supplyName"
          min-width="180"
          show-overflow-tooltip
        >
          <template #default="scope">
            <!-- {{ scope.row.supplyCode }} {{ scope.row.supplyName ? "-" : "" }} -->
            {{ scope.row.supplyName }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              :disabled="scope.row.exceptionState == 1"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              :disabled="scope.row.exceptionState == 1"
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <q8dqualityexception-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import dayjs from "dayjs";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQ8DQUALITYEXCEPTION",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/qms/q8dqualityexception/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  qualityExceptionCode: "",
  productionTypeId: "",
  productionTypeName: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  figureNumber: "",
  failureMode: "",
  occurrenceTimeSearch: [],
  occurrenceTimeStart: "",
  occurrenceTimeEnd: "",
  informationSourceId: "",
  exceptionState: "",
  isInternal: "",
  supplyId: "",
  supplyCode: "",
  supplyName: "",
  raiseUserId: "",
  isClose: "",
  createTimeSearch: [],
  createTimeStart: "",
  createTimeEnd: "",
  lastUpdateTimeSearch: [],
  lastUpdateTimeStart: "",
  lastUpdateTimeEnd: "",
  enabled: "",
  deleted: "",
};

const deleteParam = {
  api: "/qms/q8dqualityexception/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/qms/q8dqualityexception/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开质量异常信息表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改质量异常信息";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增质量异常信息";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开质量异常信息表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "质量异常信息详情";
  addDialog.readvisible = true;
  console.log(22);

  getInfo(roleObj.id);
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getoccurrenceTime(data: any) {
  if (data) {
    searchParam.value.occurrenceTimeStart = data[0];
    searchParam.value.occurrenceTimeEnd = data[1];
  } else {
    searchParam.value.occurrenceTimeStart = "";
    searchParam.value.occurrenceTimeEnd = "";
  }
}
function getcreateTime(data: any) {
  if (data) {
    searchParam.value.createTimeStart = data[0];
    searchParam.value.createTimeEnd = data[1];
  } else {
    searchParam.value.createTimeStart = "";
    searchParam.value.createTimeEnd = "";
  }
}
function getlastUpdateTime(data: any) {
  if (data) {
    searchParam.value.lastUpdateTimeStart = data[0];
    searchParam.value.lastUpdateTimeEnd = data[1];
  } else {
    searchParam.value.lastUpdateTimeStart = "";
    searchParam.value.lastUpdateTimeEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/qms/q8dqualityexception/deleteItem/${id}`,
      method: "post",
    }).then((res) => {
      ElMessage.success("删除成功");
      search();
    });
  });
}

// 产品过程列表
const materialProcessList = ref([]);
async function getMaterialProcess() {
  let res = await request({
    url: "/qms/qmsmaterialprocess/getList",
    method: "post",
    data: {},
  }).finally(() => {
    loading.value = false;
  });
  materialProcessList.value = res.data;
  console.log("materialProcessList", materialProcessList.value);
}
// const changeFigureNumber = (e) => {
//   if (e) {
//     materialProcessList.value.forEach((item) => {
//       if (item.id == e) {
//         formData.materialCode = item.materialProcessCode;
//         formData.materialName = item.materialProcessName;
//         formData.figureNumber = item.materialProcessFigure;
//       }
//     });
//   } else {
//     formData.materialCode = "";
//     formData.materialName = "";
//     formData.figureNumber = "";
//   }
// };
// 供应商列表
const supplyList = ref([]);
async function getSupplyList() {
  let res = await request({
    url: "mdm/mdmpartner/getListByFull",
    method: "post",
    data: {},
  }).finally(() => {
    loading.value = false;
  });
  supplyList.value = res.data;
  console.log("getSupplyList", supplyList.value);
}

// const changSupplyList = (e) => {
//   if (e) {
//     supplyList.value.forEach((item) => {
//       if (item.id == e) {
//         formData.supplyName = item.partnerName;
//         formData.supplyCode = item.partnerCode;
//       }
//     });
//   } else {
//     formData.supplyName = "";
//     formData.supplyCode = "";
//   }
// };
onMounted(() => {
  getMaterialProcess();
  getSupplyList();
});
</script>
